using Vboot.Core.Module.Ass;
using Vboot.Core.Module.Bpm;

namespace Vboot.Core.Module.Sys;

[ApiDescriptionSettings("Sys", Tag = "外部公司管理")]
public class SysCoopCorpApi : IDynamicApiController
{
    private readonly SysCoopCorpService _service;

    private readonly AssNumMainService _numService;
    


    [QueryParameters]
    public async Task<dynamic> GetTree()
    {
        string sql = @"select id,pid,name,'cate' type from sys_coop_cate 
            union all select id,catid as pid,name,'corp' type from sys_coop_corp";
        var treeList = await _service.repo.Context.SqlQueryable<Ztree>(sql).
            ToTreeAsync(it=>it.children,it=>it.pid, null);
        return treeList;
    }
    
    
    public SysCoopCorpApi(SysCoopCorpService service,
        AssNumMainService numService)
    {
        _service = service;
        _numService = numService;
    }

    /// <summary>
    /// 获取分页数据
    /// </summary>
    /// <returns></returns>
    [QueryParameters]
    public async Task<dynamic> Get(string name,string catid)
    {
        var pp = XreqUtil.GetPp();
        var items  = await _service.repo.Context.Queryable<SysCoopCorp, SysOrg, SysOrg,SysCoopCate>
            ((t, o, o2,c) => new JoinQueryInfos(
                JoinType.Left, o.id == t.crmid,
                JoinType.Left, o2.id == t.upmid,
                JoinType.Left, c.id == t.catid))
            .WhereIF(!string.IsNullOrWhiteSpace(name), t => t.name.Contains(name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(catid), t => t.catid==catid)
            .OrderBy(t => t.crtim, OrderByType.Desc)
            .Select((t, o, o2,c)
                =>  (dynamic) new {t.id, t.name, t.state, t.notes, t.crtim, t.uptim, t.senum, crman = o.name, upman = o2.name,catna=c.name})
            .ToPageListAsync(pp.page, pp.pageSize, pp.total);
        return RestPageResult.Build(pp.total.Value, items);
    }

    /// <summary>
    /// 获取详细信息
    /// </summary>
    /// <param name="id">DEMO ID</param>
    /// <returns></returns>
    [Oplog("DEMO详情查询")]
    public async Task<SysCoopCorp> GetOne(string id)
    {
        return await _service.Select(id);
    }

    /// <summary>
    /// 新增主数据
    /// </summary>
    // [MyUnitOfWork]
    public async Task<string> Post(SysCoopCorp main)
    {
        main.senum = _numService.getNum("DEMO");
        return await _service.Insert(main);
    }

    /// <summary>
    /// 修改主数据
    /// </summary>
    [MyUnitOfWork]
    public async Task<string> Put(SysCoopCorp main)
    {
        return await _service.Update(main);
    }

    /// <summary>
    /// 删除主数据
    /// </summary>
    [MyUnitOfWork]
    public async Task Delete(string ids)
    {
        await _service.Delete(ids);
    }
}